// utils/youdao-api.js - 有道翻译API工具类（仅用于翻译）
const CryptoJS = require('../miniprogram_npm/crypto-js/index');

class YoudaoAPI {
  constructor() {
    this.appId = '4ffda8c18fdb77d9';
    this.appSecret = 'pMFXlst8tGJez0Htc1eGZpAHvwpjegnZ';
    this.translateUrl = 'https://openapi.youdao.com/api';
  }

  // 生成有道API签名
  generateSign(query, salt, curtime) {
    const queryLength = query.length;
    let input = query;
    
    if (queryLength > 20) {
      input = query.substring(0, 10) + queryLength + query.substring(queryLength - 10);
    }
    
    const str1 = this.appId + input + salt + curtime + this.appSecret;
    const sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);
    
    return sign;
  }

  // 检测文本语言
  detectLanguage(text) {
    // 简单的语言检测：检查是否包含中文字符
    const chineseRegex = /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/;
    return chineseRegex.test(text) ? 'zh-CHS' : 'en';
  }

  // 翻译文本（自动检测语言）
  translateText(text) {
    return new Promise((resolve, reject) => {
      if (!text || typeof text !== 'string') {
        reject(new Error('请提供有效的文本'));
        return;
      }

      const salt = Math.random().toString(36).substr(2, 9);
      const curtime = Math.floor(Date.now() / 1000);
      const sign = this.generateSign(text, salt, curtime);

      // 自动检测语言并设置翻译方向
      const detectedLang = this.detectLanguage(text);
      const from = detectedLang;
      const to = detectedLang === 'zh-CHS' ? 'en' : 'zh-CHS';

      const requestData = {
        q: text,
        from: from,
        to: to,
        appKey: this.appId,
        salt: salt,
        sign: sign,
        signType: 'v3',
        curtime: curtime
      };

      wx.request({
        url: this.translateUrl,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: requestData,
        success: (res) => {
          console.log('有道翻译API响应:', res.data);
          
          if (res.statusCode === 200 && res.data.errorCode === '0') {
            const translation = res.data.translation || [];
            const result = {
              original: text,
              translated: translation[0] || text,
              from: from,
              to: to
            };
            resolve(result);
          } else {
            console.error('有道翻译API错误:', res.data);
            resolve({
              original: text,
              translated: text,
              from: from,
              to: to
            });
          }
        },
        fail: (err) => {
          console.error('有道翻译API请求失败:', err);
          resolve({
            original: text,
            translated: text,
            from: from,
            to: to
          });
        }
      });
    });
  }

  // 批量翻译meanings
  translateMeanings(meanings) {
    return new Promise((resolve) => {
      if (!meanings || meanings.length === 0) {
        resolve([]);
        return;
      }

      const translatePromises = meanings.map(meaning => {
        return this.translateText(meaning.definition).then(translationResult => {
          return {
            ...meaning,
            definition: translationResult.translated || meaning.definition
          };
        });
      });

      Promise.all(translatePromises).then(translatedMeanings => {
        resolve(translatedMeanings);
      }).catch(error => {
        console.error('批量翻译失败:', error);
        resolve(meanings); // 翻译失败时返回原始数据
      });
    });
  }
}

module.exports = YoudaoAPI;